import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText, } from '@ant-design/pro-components';
import { Alert, Form, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { history, useIntl, useModel } from 'umi';
import styles from './index.less';
import { getCurrentUserMenu, login } from '@/services/api/user';
import ReactCanvasNest from 'react-canvas-nest'

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [form] = Form.useForm();
  const [imgData, setimgData] = useState({
    png: '',
    verificationcode: '',
  });
  const intl = useIntl();

  const fetchUserInfo = async (userInfo: any) => {



    console.log(userInfo);
    const userCurrentMenu: any = await getCurrentUserMenu({});
    console.log(userCurrentMenu);
    window.currentMenus = userCurrentMenu;
    let menusKeys = {}
    userCurrentMenu.data.map((e: any, i: number) => {
      menusKeys[e.menuKey] = e
    });
    window.currentMenus = menusKeys
    let hasMenus: any = [];
    let currentMenus = userCurrentMenu?.data;
    let buttonAuth = {};
    currentMenus.map((e: any, i: number) => {
      hasMenus.push(e.menuKey);
    });
    // });
    await new Promise<void>((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, 300);
    })

    await setInitialState((s) => ({
      ...s,
      currentUser: userInfo,
      userMenusKeys: hasMenus,
      accessData: []
    }));
  };

  const handleSubmit = async (values: any) => {
    try {
      console.log(values);
      // 登录
      const msg: any = await login({
        ...values,
      });
      console.log(msg);
      if (msg?.data?.result_flag) {
        message.success('登录成功！', 1);
        await fetchUserInfo(msg.data?.data);
        debugger
        /** 此方法会跳转到 redirect 参数所在的位置 */
        history.push('/home');
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      // const defaultLoginFailureMessage = intl.formatMessage({
      //   id: 'pages.login.failure',
      //   defaultMessage: '登录失败，请重试！',
      // });
      // message.error(defaultLoginFailureMessage);
      // form.setFieldsValue({
      //   ['kaptcha']: '',
      // });
    }
  };
  const floatColor = '24,144,255'
  // useEffect(() => {
  //   form.setFieldValue('user_code', 'lianshenglu');
  //   form.setFieldValue('user_pwd', 'lianshenglu123!');
  //   handleSubmit(form.getFieldsValue())
  // }, [])
  return (
    <div className={styles.container}>
      <div className={styles.logoPng} />
      <div className={styles.content}>

        <LoginForm
          form={form}
          // logo={}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <div className={styles.loginTitle}>欢迎登录</div>
          <ProFormText
            name="user_code"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          />
          <ProFormText.Password
            name="user_pwd"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />

        </LoginForm>
        <div className={styles.other}>
          <span>还没有账号?</span>
          <a onClick={() => history.push('/user/register')}>立即注册</a>
        </div>
      </div>
      {/* <Footer /> */}
    </div>
  );
};

export default Login;
